package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollectionUtil;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.controller.admin.req.AdminSysMenuRoleListReq;
import com.wcs.exam.controller.admin.req.AdminSysMenuRoleSaveReq;
import com.wcs.exam.dao.SysMenuRoleDao;
import com.wcs.exam.dao.impl.mapper.entity.SysMenuRole;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Admin-菜单角色关联表
 *
 * @author wcs
 * @since 2024-07-06
 */
@Component
@RequiredArgsConstructor
public class AdminSysMenuRoleBiz extends BaseBiz {

    @NotNull
    private final SysMenuRoleDao dao;

    /**
     * 菜单角色关联表-列出
     *
     * @param req 菜单角色关联表-列出查询参数
     * @return 菜单角色关联表
     */
    public Result<List<Long>> list(AdminSysMenuRoleListReq req) {
        List<SysMenuRole> menuRoleList = dao.listByRoleIds(Collections.singletonList(req.getRoleId()));
        if (CollectionUtil.isNotEmpty(menuRoleList)) {
            List<Long> roleIdList = new ArrayList<>();
            for (SysMenuRole sysMenuRole : menuRoleList) {
                roleIdList.add(sysMenuRole.getMenuId());
            }
            return Result.success(roleIdList);
        }
        return Result.success(new ArrayList<>());
    }

    /**
     * 菜单角色关联表-添加
     *
     * @param req 菜单角色关联表-添加对象
     * @return 添加结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<String> save(AdminSysMenuRoleSaveReq req) {
        // 先删除该角色下所有的旧菜单
        dao.removeByRoleId(req.getRoleId());

        // 再添加该角色下所有的新菜单
        if (CollectionUtil.isNotEmpty(req.getMenuIdList())) {
            List<SysMenuRole> list = new ArrayList<>();
            for (Long menuId : req.getMenuIdList()) {
                SysMenuRole menuRole = new SysMenuRole();
                menuRole.setMenuId(menuId);
                menuRole.setRoleId(req.getRoleId());
                list.add(menuRole);
            }
            boolean saveRes = dao.saveBatch(list);
            return saveRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
        }
        return Result.success(toI18nSuccess());
    }

}
